<?php
/**
* class ItemChar
*
* Classe que proporciona les funcions i la data propies d'un user.
*
* @version 1.0
* @author Ferran Martín & Marc Sampé
* @project dcgame
*/
class User{

    private $betaMode = true;

    private $oDB;
    private $oMyFb = null;
    private $userData = null;
    private $userId = null;

    public function __construct($idUser = null){
        $this->oDB = DB::getInstance();

        if ($idUser != null) { //User per parametre
            $this->userId = $idUser;
        }
        else { //Carregar user de Facebook
            if (!$this->oMyFb) $this->oMyFb = new myFacebook ();
            if ($this->isLogged()) $this->loadUserData();
        }
    }

    /**
    * Retorna si l'usuari es un user logejat (registrat) o no (guest)
    *
    * @access public
    * @return boolean
    */
    public function isLogged(){
        if ($this->oMyFb) return $this->oMyFb->isLogged;
        else return false;
    }

    /**
    * Retorna si un usuari és admin o no.
    *
    * @access public
    * @return boolean
    */
    public function isAdmin(){
        return $this->getAtribute("is_admin");
    }
    
    /**
    * Retorna el nom del usuari.
    *
    * @access public
    * @return string
    */
    public function getName(){
        return $this->getAtribute("name");
    }

    /**
    * Indica el nom de l'usuari.
    *
    * @param string $name
    * @access public
    * @return void
    */
    public function setName($name){
        $this->setAtribute("name", $name);
    }

    /**
    * Retorna l'informació de l'usuari.
    * Segons $from retorna info i format corresponent.
    *
    * @param string $from
    * @access public
    * @return array
    */
    public function getUserData($from = "web"){
        if ($this->isLogged()) {
            if (!$this->userData) $this->loadUserData();
            switch ($from) {
                case "web":
                    return $this->userData;
                    break;
                    
                case "ajax":
                    return $this->userData;
                    break;
            }
        } else return false;
    }

    /**
    * Retorna l'identificador d'usuari
    *
    * @access public
    * @return integer
    */
    public function getUserId(){
        return $this->getAtribute("id");
    }

    /**
    * Retorna la llista d'amics
    *
    * @access public
    * @return array
    */
    public function getFriendsList() {
        if ($this->isLogged()) {
            $_aFriends = $this->oMyFb->getListFriends();           
            $aFriends = array();

            if (!empty($_aFriends)) {
                foreach ($_aFriends as $Friend) {
                        $tmp = $this->friendParser($Friend);
                        if(!empty($tmp)) $aFriends[] = $tmp;
                }
            }
            return $aFriends;
        }
        else return false;
    }

    /**
    * Crea un usuari nou.
    *
    * @access public
    * @return integer
    */
    public function createUser() {
        if ($this->isLogged()) {
            $sqlPlayer = "INSERT INTO `{$this->oDB->getTable()}` ";
            $sqlPlayer .= "(`{$this->oDB->getField("fb_uid")}`, `{$this->oDB->getField("connect")}`, ";
            $sqlPlayer .= "`{$this->oDB->getField("last_login")}`, `{$this->oDB->getField("timeout")}`) ";
            $timeout = time() + (60*5);
            $sqlPlayer .= "VALUES ('{$this->oMyFb->getId()}', 1, ".time()." , {$timeout})";
            $rsPlayer = $this->oDB->execute($sqlPlayer);

            if ($rsPlayer) return $this->oDB->lastInsertedId();
            else return false;

        } else return false; 
        
    }

     /**
     * Funcio per accedir als errors generats per la llibreria myFacebook
     *
     * @access public
     * @return array
     */
    public function getmyFbErrors() {
        return $this->oMyFb->myFb_errors;
    }

    /**
     * Funcio per saber si existeix un usuari amb id = $idUser
     *
     * @param int $idUser
     * @return bool
     */
    private function isUserById($idUser) {
        $sql = "SELECT * FROM `{$this->oDB->getTable("Player")}` ";
        $sql .= "WHERE `{$this->oDB->getField("Player", "id")}` = ".$this->oDB->escape($idUser);
        $rs = $this->oDB->queryUniqueValue($sql);
        if ($rs != null) return true;
        else return false;
    }

    /**
    * Abtraccio del "gets" i els "is"
    *
    * @access private
    * @return string or boolean or int
    */
    private function getAtribute($attrName) {
        $field = $this->oDB->getField("Player", $attrName);
        if ($field && $this->isLogged()) {
            if (!$this->userData) $this->loadUserData();
            return $this->userData[$field];
        }
        //user carregat per parametre (no logejat per facebook)
        else if ($field && $this->userId) {
            $sql = "SELECT {$field} FROM {$this->oDB->getTable("Player")} ";
            $sql .= "WHERE {$this->oDB->getField("Player", "id")} = {$this->userId}";
            $rs = $this->oDB->queryUniqueValue($sql);
            if ($rs != null) return $rs[$field];
            else return false;
        }
        else return false;
    }

    /**
     * Abstraccio dels "sets"
     *
     * @access private
     * @return boolean
     */
    private function setAtribute($attr, $value) {
        $field = $this->oDB->getField("Player", $attr);
        if ($field && $this->havePerms()) {
            $sql = "UPDATE {$this->oDB->getTable("Player")} SET {$field} = {$this->oDB->escape($value)} ";
            $sql .= "WHERE {$this->oDB->getField("Player", "id")} = ".$this->userId;
            $this->oDB->execute($sql);  
            $this->loadUserData();
        } else return false;
    }

    /**
    * Carrega tot la informació de l'user
    *
    * @access private
    * @return void
    */
    private function loadUserData(){
        $this->oDB->selectTable("User");
        $sql = "SELECT * FROM `{$this->oDB->getTable()}` ";
        $sql .= "WHERE `{$this->oDB->getField("fb_uid")}` = '".$this->oMyFb->getId()."'";
        $userData = $this->oDB->queryUniqueValue($sql);
        if ($userData) {
            $this->userData = $userData;
            $this->userId = $userData[$this->oDB->getField("id")];
        } else {
            if ($idUser = $this->createUser()) {
                $sql = "SELECT * FROM `{$this->oDB->getTable()}` ";
                $sql .= "WHERE `{$this->oDB->getField("id")}` = '{$idUser}'";
                $userData = $this->oDB->queryUniqueValue($sql);
                if ($userData) {
                    $this->userData = $userData;
                    $this->userId = $idUser;
                }
            }
        }
        $this->oDB->deselectTable();
    }
}
?>
